package com.baitiaojun.system.admin.service.user.impl;

import com.baitiaojun.common.enums.impl.*;
import com.baitiaojun.common.exception.ServerException;
import com.baitiaojun.common.exception.ServiceException;
import com.baitiaojun.common.utils.date.DateTimeUtils;
import com.baitiaojun.common.utils.desensitize.RSAUtil;
import com.baitiaojun.log.core.annotation.OperLog;
import com.baitiaojun.security.core.utils.SecurityUtils;
import com.baitiaojun.system.admin.controller.user.req.UserRegisterReq;
import com.baitiaojun.system.admin.helper.CaptchaHelper;
import com.baitiaojun.system.admin.mapper.user.UserMapper;
import com.baitiaojun.system.admin.pojo.SysUserDO;
import com.baitiaojun.system.admin.service.user.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUserDO> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CaptchaHelper captchaHelper;

    @Transactional
    @OperLog(title = "UserServiceImpl.userRegister",
            businessTypeEnums = ServiceTypeEnums.INSERT,
            operatorTypeEnums = OperatorTypeEnums.MOBILE)
    @Override
    public void userRegister(UserRegisterReq registerReq) {
        captchaHelper.validateCaptcha(registerReq.getCaptchaId(), registerReq.getCaptcha());

        //检查用户是否存在
        boolean exists = userMapper.exists(registerReq.getUsername());
        if (exists) {
            throw new ServiceException(ServiceExpEnums.EXP_EXISTS_REGISTER_USER);
        }

        //创建新用户
        SysUserDO userDO = new SysUserDO();
        String username = registerReq.getUsername();
        userDO.setUserName(username);
        userDO.setNickName("普通用户");
        String decryptPass;
        try {
            decryptPass = RSAUtil.decrypt(registerReq.getPassword());
        } catch (Exception e) {
            throw new ServerException(ServerExpEnums.EXP_PASS_DECRYPT_ERROR);
        }
        userDO.setPassword(SecurityUtils.encodePassword(decryptPass));
        String ok = String.valueOf(UserStatusEnums.OK.getCode());
        userDO.setStatus(ok);
        userDO.setDelFlag(ok);
        userDO.setCreateBy(username);
        userDO.setCreateTime(DateTimeUtils.parseDate(DateTimeUtils.getDateTime()));
        boolean register = userMapper.createUser(userDO);
        if (!register) {
            throw new ServiceException(ServiceExpEnums.EXP_BAD_REGISTER_USER);
        }
    }
}
